package com.lute.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.security.oauth2.common.json.JSONException;
import org.springframework.security.oauth2.common.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lute.json.CalendarEntriesJSON;
import com.lute.model.Approver;
import com.lute.model.ClientAccountingPeriodState;
import com.lute.model.ClientAdmin;
import com.lute.model.Employee;
import com.lute.model.EmployeeAccountingPeriod;
import com.lute.model.EmployeeAccountingPeriodState;
import com.lute.model.EmployeeEntry;
import com.lute.model.User;
import com.lute.model.UserEntitlement;
import com.lute.utils.ServerErrorResponse;


@Controller
public class CurrentAccountingPeriodServlet {
	
	@RequestMapping(value="/currentAccountingPeriod", method= RequestMethod.POST, headers="Content-type=application/json") 
	public @ResponseBody String currentAccountingPeriod(@RequestBody String employeeIdJSON,HttpServletRequest request) throws JSONException {
		String result = "";
		JSONObject jsonReq;
		JSONObject jsonRes = new JSONObject();
		
		HttpSession session = request.getSession(false);
		if(session == null) {
			jsonRes.put("result", ServerErrorResponse.USER_NOT_LOGGED_IN.toString());
			result = jsonRes.toString();
			return result;
		}
		
		try {
			jsonReq = new JSONObject(employeeIdJSON);
		} catch(JSONException e) {
			jsonRes.put("result", ServerErrorResponse.MALFORMED_REQUEST.toString());
			result = jsonRes.toString();
			return result;
		}
		
		String userId_str = jsonReq.getString("userId");
		int userId = Integer.parseInt(userId_str);
	    int sessionUserId = (Integer)session.getAttribute("sessionUserId");
		String role = (String)session.getAttribute("role");
		jsonRes.put("result", "");
		
		EmployeeAccountingPeriod employeeAccountingPeriod = null;

		employeeAccountingPeriod = UserEntitlement.checkUserPrivilegeToEmployeeAccountingPeriod("",sessionUserId,userId,role,jsonRes);
		
		if(!(jsonRes.get("result").equals(""))) {
			result = jsonRes.toString();
			return result;
		}
		
		if(employeeAccountingPeriod == null) {
			jsonRes.put("result", ServerErrorResponse.UNKNOWN_ACCOUNTING_PERIOD.toString());
			result = jsonRes.toString();
			return result;
		}
	
		SimpleDateFormat fromToDateFormater = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat rejectionDateFromater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<CalendarEntriesJSON> calendarEntries = new ArrayList<CalendarEntriesJSON>();
		
		try {
		
			List<EmployeeEntry> employeeEntries = employeeAccountingPeriod.getEmployeeEntries();
			
			CalendarEntriesJSON calendarEntriesJSON = null;
			for(EmployeeEntry empEntry: employeeEntries) {
				calendarEntriesJSON = new CalendarEntriesJSON();
				calendarEntriesJSON.setDate(fromToDateFormater.format(empEntry.getDate().getTime()));
				calendarEntriesJSON.setCompanyCategory(empEntry.getCompanyCategory().getName());
				calendarEntriesJSON.setCreativeHours(Integer.toString(empEntry.getCreativeHours()));
				calendarEntriesJSON.setHours(Integer.toString(empEntry.getHours()));
				calendarEntries.add(calendarEntriesJSON);
			}
			
			jsonRes.put("rejectedBy", JSONObject.NULL);
			//jsonRes.put("rejectionReason",JSONObject.NULL);
			jsonRes.put("rejectionDate", JSONObject.NULL);
			
			jsonRes.put("result", "OK");
			jsonRes.put("userId", userId_str);
			jsonRes.put("from", fromToDateFormater.format(employeeAccountingPeriod.getClientAccountingPeriod().getDate_from().getTime()));
			jsonRes.put("to", fromToDateFormater.format(employeeAccountingPeriod.getClientAccountingPeriod().getDate_to().getTime()));
			jsonRes.put("clientAccountingPeriodState", "open");
			jsonRes.put("employeeAccountingPeriodState", employeeAccountingPeriod.getEmployeeAccountingPeriodState());
			if(employeeAccountingPeriod.getRejectionReason() != null) {
				if(employeeAccountingPeriod.getEmployeeAccountingPeriodState().equals(EmployeeAccountingPeriodState.REJECTED_BY_APPROVER.toString()) || 
				   employeeAccountingPeriod.getEmployeeAccountingPeriodState().equals(EmployeeAccountingPeriodState.REJECTED_BY_CLIENT_ADMIN.toString())) {
					
					jsonRes.put("rejectionReason",employeeAccountingPeriod.getRejectionReason());
					if(employeeAccountingPeriod.getRejectedBy() != null) {
						jsonRes.put("rejectedBy", employeeAccountingPeriod.getRejectedBy());
					}
					if(rejectionDateFromater.format(employeeAccountingPeriod.getRejectionDate().getTime()) != null) {
						jsonRes.put("rejectionDate", rejectionDateFromater.format(employeeAccountingPeriod.getRejectionDate().getTime()));
					}
				}
			}
			
		}catch(NullPointerException npe) {
			jsonRes.put("result", ServerErrorResponse.INTERNAL_ERROR.toString());
			result = jsonRes.toString();
			return result;
		}
		jsonRes.put("calendarEntries", calendarEntries);
		result = jsonRes.toString();
		return result;
	}
}